/**
 * 
 */
package com.iwords.service.ao.impl;

import com.iwords.service.AccountService;

import com.iwords.service.AccountServiceLocal;
import com.iwords.service.UserServiceLocal;
import javax.ejb.Stateless;

import com.iwords.service.object.AccountEntity;
import com.iwords.service.object.UserEntity;
import java.util.Date;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author    	huangbaichuan 
 * @time      	2011-8-14    
 * @description	  
 */
@Stateless
public class AccountServiceImpl extends AbstractFacade<AccountEntity> implements AccountService, AccountServiceLocal {

    @PersistenceContext(unitName = "iwords")
    private EntityManager em;
    @EJB
    UserServiceLocal userService;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public AccountServiceImpl() {
        super(AccountEntity.class);
    }

    @Override
    public boolean updateAccountForAlipay(AccountEntity account) {
        if (account == null || account.getId() == null) {
            throw new IllegalArgumentException("can not handle an null object account");
        }
        AccountEntity accountEntity = this.find(account.getId());
        if (accountEntity == null) {
            return false;
        }

        if (accountEntity.getStatus().equals(AccountEntity.FINISHED_PAY)) {
            //已经回调过
            return true;
        }

        accountEntity.setAlipayEmail(account.getAlipayEmail());
        accountEntity.setStatus(AccountEntity.FINISHED_PAY);
        accountEntity.setAlipayNumber(account.getAlipayNumber());
        accountEntity.setUpdatetime(new Date());
        this.edit(accountEntity);

        //更新用户过期时间
        UserEntity user = new UserEntity();
        user.setUserid(accountEntity.getUserid());
        this.userService.updateUserVacationFormNow(user, 365);
        //更新用户的教师ID
        if (accountEntity.getTeacherid() != null) {
            UserEntity userEntity = userService.find(accountEntity.getUserid());
            userEntity.setTeacherid(accountEntity.getTeacherid());
            userService.edit(userEntity);
        }
        return true;
    }
}
